package com.michaelbulava.TFS.ui.controls.connect;

import com.michaelbulava.TFS.Messages;
import com.michaelbulava.TFS.ui.framework.validation.AbstractTextControlValidator;
import com.microsoft.tfs.util.valid.IValidity;
import com.microsoft.tfs.util.valid.Validity;

import javax.swing.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.MessageFormat;

/**
 * Created by mbulava on 6/15/2015.
 */
public class TextControlURLOrHostnameValidator extends AbstractTextControlValidator{

    private String fieldName;
    private final boolean required;
    private URL url;

    protected TextControlURLOrHostnameValidator(JTextField subject, String fieldName, boolean required) {
        super(subject);
        this.fieldName = fieldName;
        this.required = required;

        validate();
    }

    public void setFieldName(String fieldName){
        this.fieldName = fieldName;
    }

    public URL getURL(){
        return this.url;
    }

    @Override
    protected IValidity computeValidity(String text) {
        text = text.trim();
        if (text.length() == 0)
        {
            this.url = null;
            if (this.required) {
                return Validity.invalid(MessageFormat.format(Messages.getString("TextControlUrlOrHostnameValidator.MustEnterValueForFieldFormat"),
                        new Object[]{this.fieldName}));
            }
            return Validity.VALID;
        }
        try
        {
            this.url = new URL(text);
        }
        catch (MalformedURLException e)
        {
            try
            {
                this.url = new URL("http", text, 80, "/");
            }
            catch (MalformedURLException f)
            {
                this.url = null;

                String message = MessageFormat.format(Messages.getString("TextControlUrlOrHostnameValidator.EnterValidUrlOrHostnameFormat"),
                        new Object[] { this.fieldName });



                return Validity.invalid(message);
            }
        }
        if ((this.url.getHost() == null) || (this.url.getHost().length() == 0)) {
            return Validity.invalid(MessageFormat.format(Messages.getString("TextControlUrlOrHostnameValidator.EnterValidUrlOrHostnameFormat"),
                    new Object[] { this.fieldName }));
        }
        if (this.url.getHost().indexOf('_') != -1) {
            return Validity.invalid(Messages.getString("TextControlUrlOrHostnameValidator.UnderscoreNotAllowedInHostname"));
        }
        return Validity.VALID;
    }

}
